package crazyjava;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newCachedThreadPool();
		final Semaphore sp = new Semaphore(3);
		for(int i=0;i<10;i++){
		
			threadPool.submit(new Runnable() {
				
				public void run() {
					
					try {
						sp.acquire();
						System.out.println(Thread.currentThread().getName()+" 获得资源，当前共有"+(3-sp.availablePermits())+"正在访问资源");
						Thread.sleep((new Random().nextInt(10)+1)*1000);
						sp.release();
						System.out.println(Thread.currentThread().getName()+" 释放资源，当前共有"+(3-sp.availablePermits())+"正在访问资源");
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			});
		}
		threadPool.shutdown();

	}

}
